/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 * \file
 * \brief MaCI - ObjectDB Interface Client header
 * \author Antti Maula <antti.maula@tkk.fi>
 *
 * $Id: ObjectDBClient.hpp,v 1.2 2009-08-31 12:58:15 amaula Exp $
 *
 */
#ifndef _MACI_INTERFACE_OBJECTDBCLIENT_HPP_
#define _MACI_INTERFACE_OBJECTDBCLIENT_HPP_

#include "MaCI.hpp"
#include "thread.hpp"
#include "sync.hpp"
#include <vector>

// These are not necessarily required here, but defined to make the
// interface easier to include.
#include "ObjectDBData.hpp"
#include "DBObject.hpp"

// Forward declare gimi::GIMI
namespace gimi {
  class GIMI;
}

namespace MaCI {
  namespace ObjectDB {

    
    // Forward declaration.
    class CObjectDBData;
    class CObjectDBClient;

    
    /** Callback interface class for ObjectDB interface.
     *
     * This interface defines functions which can be used for
     * ObjectDBClient callbacks. These functions are executed (more
     * detail per function basis) as new data arrives, and directly
     * from the context of the receiving thread. <b>Therefore, it is
     * important that the handling function is as simple and fast as
     * possible, as it will block the execution of the receiving
     * thread while executed.</b>
     */
    class CObjectDBClientCallback
    {
    public:

      CObjectDBClientCallback() {}
      virtual ~CObjectDBClientCallback() {}


      /** Handler function for ObjectDBData event.
       *
       * This function is called when the ObjectDBClient receives new
       * data from the server.
       *
       * \note <b>Keep this function simple & fast as it will block the 
       * data receiving thread while executing!</b>
       *
       * @param[in] aData       Constant reference to CObjectDBData element 
       *                        containing the received event.
       * @param[in] aDataSequence Sequence number of the received data. 
       *                        This should increment by one on each call.
       * @param[in] aObjectDBClient Reference to ObjectDBClient 
       *                        instance which received this event.
       */
      virtual void OnObjectDBDataEvent(const CObjectDBData &aData, 
                                    const unsigned int aDataSequence,
                                    CObjectDBClient &aObjectDBClient) = 0;
    };

    /** ObjectDB event types.
     */
    enum EObjectDBEvent {
      KEventObjectDBData = 0 ///< ObjectDBData element received and stored.
    };


    /** MaCI - ObjectDB Client interface.
     * 
     * This class contains the methods and types for using
     * a MaCI::ObjectDB service in the GIMnet.
     */
    class CObjectDBClient 
      : private gim::CSync,
        private gim::CThread,
        public MaCI::CMaCI
    {
    public:
      /** Constructor.
       * 
       * Constructor of the ObjectDBClient. This requires;
       * a pointer to Initialized and connected GIMI, minor
       * number of this interface (Used as GIMI minor number)
       *
       * @param[in] aGIMIPtr Pointer to GIMI used for communication
       * @param[in] aInterfaceMinor Interface minor number. Usually
       *            used to indicate the instance of devices of same
       *            type. Can be left out if MaCISL is used.
       */     
      CObjectDBClient(gimi::GIMI *aGIMIPtr, const int aInterfaceMinor = -1);

      
      /** Destructor.
       */
      ~CObjectDBClient();
      

      /** Generate (Create) a new RealObject.
       *
       * This function creates a new unique Real object on the
       * database, returning its initial information for further
       * handling.
       *
       * \note This function applies the object to the database, and
       * when the function returns, the database is up-to-date.
       *
       * @param[in] aName       Name of object to create.
       *                        (64 bytes max)
       * @param[in] aType       Type of object (for example; Door, Corridoor, Room, Robot, etc.)
       *                        (32 bytes max)
       * @param[in] aDescription Freeform description of object. (4 kilobytes max)
       * @param[in] aTimeout_ms Timeout for operation to complete.
       * @return                New object handle if succesfull, zero on error (zero
       *                        is not valid object handle)
       *
       */
      TDBObjectHandle GenerateRealObject(const std::string &aName,
                                         const std::string &aType = "",
                                         const std::string &aDescription = "",
                                         const unsigned int aTimeout_ms = 2000);
      
#if 0  
      
      GetRealObjectPose(MaCI::Position::TPose3D &aPose, const CDBObject &aObject);
      SetRealObjectPose();


      SetRealObjectOrientation();
      GetRealObjectOrientation();

      SetRealObjectBoundingBox();
      GetRealObjectBoundingBox();

      GetRealObjectsInArea(Pose, BoundingBox);
      GetRealObjectInformation(objectID A);
      GetRealObjectsByType(name);
      GetRealObjectsByName(name);

      GenerateLinkBetweenRealObjects(objectID A, ObjectID B);
      GetLinksForRealObject(ObjectID A);
#endif      
      
      /** Assigns the ObjectDB client callback function. 
       *
       * This sets a function object for calling a position client
       * callback. If this is set, the interface calls the assigned
       * functions immediately when event is available.
       * 
       * \note As the function is run in the context of the receiving
       * thread, user must make sure that the callback function is
       * fast. As if the function executes too long, receiving events
       * is interrupted.
       *
       * @param[in] aObjectDBClientCallback Pointer to class implementing the interface
       *                                 CObjectDBClientCallback.
       */
      void SetObjectDBClientCallback(CObjectDBClientCallback *aObjectDBClientCallback) {
        iObjectDBClientCallback = aObjectDBClientCallback;
      }

    protected:
      /** Open client interface.
       *
       * Implementation of Open() for the class. This function is
       * called by the base class CMaCI::Open() function.
       */
      EMaCIError DoOpen(void);
      
      
      /** Close client interface.
       *
       * Implementation of Close() for the class. This function is
       * called by the base class CMaCI::Close() function.
       */
      EMaCIError DoClose(void);

      bool GetCommandReply(CObjectDBData &aData, const int aMessageID, 
                           const int aTimeout_ms);
      bool SendCommand(const CObjectDBData &aObjectDBData, const int aMessageID);
  
    private:
      /// Thread runner function. Is in charge of receiving events.
      int ThreadFunction(const int aThreadNumber);
      int ProcessMessage(const gimi::GIMIMessage &msg);

      //data.
      unsigned int iObjectDBDataSequence; ///< Received data sequence
      unsigned int iObjectDBCommandSequence; ///< Last sent Command sequence.
      CObjectDBData iLastObjectDBData; ///< Last element available
      CObjectDBClientCallback *iObjectDBClientCallback; ///< Pointer to class instance containing callback functions.

      // Override copy & assignment operator privately to disable class copying.
      CObjectDBClient(const CObjectDBClient &)
        : CSync(1,1),
          CThread(1),
          CMaCI(NULL, 0, 0, ""),
          iObjectDBDataSequence(),
          iObjectDBCommandSequence(),
          iLastObjectDBData(),
          iObjectDBClientCallback() {}
      CObjectDBClient &operator=(const CObjectDBClient &) { return *this; }
    };


  }
}

#endif //_MACI_INTERFACE_OBJECTDBCLIENT_HPP_
